"""
    示例：USDA食品数据库

    网址：http://ashleyw.co.uk/project/food-nutrient-database
"""
import numpy as np
from pandas import Series, DataFrame
import pandas as pd
import re
import json


def test_01():
    """
    :return:
    """
    db = json.load(open('foods-2011-10-03.json'))
    # print(len(db))
    # print(db[0].keys())
    # print(db[0]['nutrients'][0])
    # print(db[0]['nutrients'])
    # nutrients = DataFrame(db[0]['nutrients'])
    # print(nutrients)
    # print(nutrients[:7])

    # # 在将字典列表转换为DataFrame时，可以只抽取其中的一部分字段。
    info_keys = ['description', 'group', 'id', 'manufacturer']
    info = DataFrame(db, columns=info_keys)
    # # print(info[:5])
    # # print(info)
    # print(pd.value_counts(info.group)[:10])

    nutrients = []
    for rec in db:
        fnuts = DataFrame(rec['nutrients'])
        fnuts['id'] = rec['id']
        nutrients.append(fnuts)

    nutrients = pd.concat(nutrients, ignore_index=True)
    # print(nutrients)
    # print(nutrients.duplicated().sum())
    # 丢弃重复项
    nutrients = nutrients.drop_duplicates()
    # print(nutrients)
    # 重命名
    col_mapping = {'description': 'food',
                   'group': 'fgroup'}
    info = info.rename(columns=col_mapping, copy=False)
    # print(info)
    col_mapping = {'description': 'nutrient',
                   'group': 'nutgroup'}
    nutrients = nutrients.rename(columns=col_mapping, copy=False)
    # print(nutrients)
    # 将info跟nutrients合并起来
    ndata = pd.merge(nutrients, info, on='id', how='outer')
    # print(ndata)
    # print(ndata.ix[30000])

    # 根据营养分类得出的锌中位值
    result = ndata.groupby(['nutrient', 'fgroup'])['value'].quantile(0.5)
    result['Zinc, Zn'].sort_values().plot(kind='barh')
    by_nutrient = ndata.groupby(['nutgroup', 'nutrient'])
    get_maximum = lambda x: x.xs(x.value.idxmax())
    get_minimum = lambda x: x.xs(x.value.idxmin())
    max_foods = by_nutrient.apply(get_maximum)[['value', 'food']]
    max_foods.food = max_foods.food.str[:50]
    print(max_foods.ix['Amino Acids']['food'])


def main():
    test_01()


if __name__ == '__main__':
    main()
